$(function () {
    // IScroll
    // _loadingStep: 加载状态0默认，1显示加载状态，2执行加载数据，只有当为0时才能再次加载，这是防止过快拉动刷新
    var _myScroll, _pullUpEl, _pullUpL, _pagecount = 1, _loadingStep = 0;
    var _nodata = false, _isdisplayFilter = false, _isshowend = false, _pageparams, _filterdata;
    var _contentheight = ($(window).height() - 87);

    // 计数器（用于判断单击次数，默认最新选中）
    var _tapcount = 1;
    var goodsListPage = function () {
        this.init();
    };

    goodsListPage.prototype = {
        // 初始化
        init: function () {
            _pageparams = {
                searchword: getUrlParam("searchword"),
                catalog: getUrlParam("catalog"),
                isOnlyStarsGoods: getUrlParam("isOnlyStarsGoods") ? true : false
            };
            // 搜索条件
            if (_pageparams && _pageparams.searchword) {
                $("#searchinput").val(_pageparams.searchword);
            }
            this.loaddata(true);
            this.bindEvent();
            this.initIscroll();
        },

        // 查询数据(用于切换展示样式)
        goodslistdata: [],

        // 加载商品列表数据
        loaddata: function (isreload) {
            var model = this;            // 分类页
            var postdata = {
                "index": _pagecount,
                "size": 16,
                "query": _pageparams.searchword,
                "sorting": this.condition(),
                "search": {"source": 3}
            };

            // 分类
            if (_pageparams && _pageparams.catalog) {
                postdata.search["catalog"] = _pageparams.catalog;
            }

            // 星币商品
            if (_pageparams && _pageparams.isOnlyStarsGoods) {
                postdata.search["starsku"] = "1";
            }

            // 筛选数据
            if (_filterdata) {
                postdata.search["catalog"] = (_filterdata.catalog) ? _filterdata.catalog : postdata.search["catalog"];
                postdata.search["brand"] = (_filterdata.brand) ? _filterdata.brand : postdata.search["brand"];
                postdata.search["price"] = (_filterdata.price) ? _filterdata.price : postdata.search["price"];
                postdata.search["specs"] = (_filterdata.specs) ? _filterdata.specs : postdata.search["specs"];
            }

            if (_pagecount == 1) {
                $.showWaiting();
            }
            $.ajax({
                headers: {'Content-Type': 'application/json'},
                type: 'POST',
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/search",
                data: JSON.stringify(postdata),
                dataType: "json"
            }).done(function (res) {
                var goodslistdata = res.data;
                model.paintGoodsItem(goodslistdata, isreload);
                model.datahandler(goodslistdata, isreload);
            }).fail(function () {

            }).always(function () {
                $.closeWaiting();
            });

            if (_pagecount == 1) {
                _filterPage.loaddata(postdata);
            }
        },

        // 条件
        condition: function () {
            var condition = null;
            var activeli = $('#sortTab label[class=hover]').parents("li");
            switch (activeli.attr("tip")) {
                // 新品
                case "1":
                    condition = {"new": "DESC"};
                    break;
                // 人气
                case "2":
                    condition = {"comments": "DESC"};
                    break;
                // 价格
                case "3":
                    condition = {"price": _tapcount % 2 == 0 ? "DESC" : "ASC"};
                    break;
                // 销量
                case "4":
                    condition = {"sales": "DESC"};
                    break;
                // 筛选
                case "5":
                    break;
                default:
                    break;
            }

            return condition;
        },

        // 数据处理
        datahandler: function (goodslistdata, isreload) {
            // 显示没有查询记录
            _nodata = (goodslistdata.length == 0 && isreload);
            if (_nodata) {
                $("#pullUp").hide();
                $("#nodatadiv").show();
            } else {
                $("#nodatadiv").hide();
            }

            if (goodslistdata.length > 0 && isreload) {
                this.goodslistdata = goodslistdata;
            }

            // 若我数据页码不变
            if (_pagecount != 1 && goodslistdata.length == 0) {
                _pagecount = _pagecount - 1;
            }
        },

        // 画列表
        paintGoodsItem: function (goodslistdata, isreload) {
            if (isreload) {
                _pagecount = 1;
                _isshowend = false;
                $("#pullUp").show();
                $("#goodsitemlist").html("");
            }

            var style = $("#btnswitch").find("i").attr("tip");
            var html = [];
            if (style == 1) {
                // 横排


                $.each(goodslistdata, function (i, goodsitem) {
                    html.push("<div class='spsslbnr mbtopbottom'  name='goodsitem'  tip='" + goodsitem.sku_id + "'>");
                    html.push("<p class='spsslb-img'><a><img  class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "' src='../../images/place/496x466.png'></a></p>");
                    html.push("<div class='spsslb'>");
                    html.push("<p class='dpmc'>" + goodsitem.shop_name + "</p>");
                    html.push("<p class='spjj'>" + goodsitem.name + goodsitem.specs + "</p>");
                    html.push("<p class='spjj'>" + goodsitem.title + "</p>");
                    if (goodsitem.Is_coin == 1) {
                        html.push("<p class='jinqian mtop5'><span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsitem.coin + "</span>+<span class='money'>￥" + goodsitem.sku_actprice + "</span></p>");
                    } else {
                        html.push("<p class='spjge mtop5'><span>￥" + goodsitem.shop_price + "</span><i>市场价：" + goodsitem.market_price + "</i></p>");
                    }

                    html.push("<p class='plxsl'><span>&bull;</span>" + goodsitem.comments + "人评论/月销量" + goodsitem.sales + "</p>");
                    html.push("</div></div>");
                });
            } else if (style == 2) {
                // 竖排
                html.push("<ul class='cnxhd'>");
                $.each(goodslistdata, function (i, goodsitem) {
                    html.push("<li class='syxhd'><div name='goodsitem' tip='" + goodsitem.sku_id + "'><dl>");
                    html.push("<dt><b class='tbdw'></b><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "' src='../../images/place/496x466.png'></dt>");
                    html.push("<dd class='dpmc'>" + goodsitem.shop_name + "</dd>");
                    html.push("<dd class='spjj'>" + goodsitem.name + goodsitem.specs + "</dd>");
                    html.push("<dd class='spjj'>" + goodsitem.title + "</dd>");
                    if (goodsitem.Is_coin == 1) {
                        html.push("<dd class='jinqian'><span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsitem.coin + "</span>+<span class='money'>￥" + goodsitem.sku_actprice + "</span></dd>");
                    } else {
                        html.push("<dd class='spjge'><span>￥" + goodsitem.shop_price + "</span><i>市场价：" + goodsitem.market_price + "</i></dd>");
                    }
                    html.push("</dl></div></li>");
                });
                html.push("</ul>");
            } else if (style == 3) {

            }

            // 显示END
            if ((_pagecount > 1 && goodslistdata.length == 0) || (goodslistdata.length > 0 && _pagecount == 1 && goodslistdata.length < 16)) {
                _isshowend = true;
                $("#pullUp").hide();
                html.push("<div id='enddiv' style='margin-top:18px;margin-bottom: 20px;'><div class='with-line'>看完了</div></div>");
            }

            $("#goodsitemlist").append(html.join(""));
            $('img.lazy').lazyload({placeholder: "../../images/white.gif", threshold: 100, failure_limit: 10});
            _myScroll.refresh();
        },
        // 绑定事件
        bindEvent: function () {
            var model = this;
            // 返回
            $("#back").on("tap", function () {
                back();
            });

            // 切换展示样式
            $("#btnswitch").on("tap", function () {
                var itag = $("#btnswitch").find("i");
                var style = itag.attr("tip");
                var classname;
                if (style == "1") {
                    style = "2";
                    classname = "iconfont icon-liebiaoshitu";
                }
                else if (style == "2") {
                    style = "1";
                    classname = "iconfont icon-list";
                }
                else if (style == "3") {
                    style = "1";
                    classname = "iconfont icon-list";
                }
                itag.attr({"class": classname, "tip": style});

                _pagecount = 1;
                model.displayFilter(false);

                if (!_nodata) {
                    model.paintGoodsItem(model.goodslistdata, true);
                }
            });

            // 置顶
            $("#gotop").on("tap", function () {
                _myScroll.scrollTo(0, 0, 800);
                $('html,body').animate({scrollTop: '0px'}, 500);
            });

            // 排序Tab
            var activeli = $('#sortTab li:first-child');
            $("#sortTab li").on("tap", function () {
                var targetli = $(this);
                var targetlitip = targetli.attr("tip");

                //  最新 / 人气 / 销量
                if (["1", "2", "4"].indexOf(targetlitip) > -1) {
                    if (activeli.attr("tip") == targetlitip) {
                        return;
                    }
                    targetli.find("label").addClass("hover");
                    activeli.find("label").removeClass("hover");
                    activeli.find("i").removeClass("hover");

                    activeli = targetli;
                    model.loaddata(true);
                } else if (targetlitip == "3") {             // 价格
                    if (activeli.attr("tip") == targetlitip) {
                        _tapcount = _tapcount + 1;
                        if (_tapcount % 2 == 0) {
                            $(targetli.find("i")[1]).addClass("hover");
                            $(targetli.find("i")[0]).removeClass("hover");
                        } else {
                            $(targetli.find("i")[0]).addClass("hover");
                            $(targetli.find("i")[1]).removeClass("hover");
                        }
                    } else {
                        _tapcount = 1;
                        targetli.find("label").addClass("hover");
                        $(targetli.find("i")[0]).addClass("hover");
                        activeli.find("label").removeClass("hover");
                    }

                    activeli = targetli;
                    model.loaddata(true);
                } else {
                    // EMPTY
                }

                // 判断筛选页面是否显示
                if (targetlitip == "5" && !_filterPage.isdisplay) {
                    model.displayFilter(true);
                } else {
                    model.displayFilter(false);
                }
            });

            // 搜索
            $("#searchdiv").on("tap", function () {
                showSearchPage();
                model.displayFilter(false);
            });

            // 筛选确定
            _filterPage.confirm = function (filterdata) {
                _filterdata = filterdata;
                _pagecount = 1;
                model.loaddata(true);
                _filterPage.hide();
                $("#goodslistdiv").show();
            };
            // 筛选取消
            _filterPage.cancle = function () {
                _filterPage.hide();
                $("#goodslistdiv").show();
            };

            // 商品详情
            $("#goodsitemlist").on("click", "div[name=goodsitem]", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });
        },


        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = (y * -1);
            if (top > _contentheight / 2) {
                $('#gotop').show();
            } else {
                $('#gotop').hide();
            }
        },

        // 初始化Iscroll
        initIscroll: function () {
            var model = this;
            _pullUpEl = $('#pullUp');
            _pullUpL = _pullUpEl.find('._pullUpLabel');

            _myScroll = new IScroll('#wrapper', {
                probeType: 2,
                scrollbars: true,
                mouseWheel: false,
                fadeScrollbars: true,
                bounce: true,
                interactiveScrollbars: false,
                shrinkScrollbars: 'scale',
                click: true,
                tap: true,
                keyBindings: true,
                momentum: true
            });
            //滚动时
            _myScroll.on('scroll', function () {

            });
            //滚动完毕
            _myScroll.on('scrollEnd', function () {
                if (this.y <= 5 && this.y < (this.maxScrollY + 10)) {
                    if (_isshowend || _nodata) {
                        return;
                    }
                    pullUpAction();
                }

                $('img.lazy').lazyload({
                    placeholder: "../../images/grey.gif",
                    container: $("#wrapper"),
                    threshold: 100,
                    failure_limit: 10
                });
                model.isDisplayTopIcon(this.y);
            });

            // 上拉显示更多
            function pullUpAction() {
                setTimeout(function () {
                    _pagecount = _pagecount + 1;
                    model.loaddata();
                    _pullUpEl.removeClass('loading');
                    _pullUpL.html('上拉显示更多...');
                    _myScroll.refresh();
                    _loadingStep = 0;
                }, 1000);
            }

            document.addEventListener('touchmove', function (e) {
                if (!(_isdisplayFilter)) {
                    e.preventDefault();
                }
            }, false);
        },

        // 显示筛选页
        displayFilter: function (display) {
            if (display) {
                _isdisplayFilter = true;
                _filterPage.show();
                $("#goodslistdiv").hide();
            } else {
                _isdisplayFilter = false;
                _filterPage.hide();
                $("#goodslistdiv").show();
            }
        }
    };


    // 筛选页
    var _filterPage = new filterPage();

    var _goodsListPage = new goodsListPage();

    // 搜索
    search = function (searchword) {
        $("#searchiframe").hide();
        if (searchword.indexOf('|') > -1) {
            var searchcontion = searchword.split('|');
            _pageparams.catalog = searchcontion[0];
            _pageparams.searchword = searchcontion[1];
            $("#searchinput").val(searchcontion[1]);
        } else {
            _pageparams.catalog = "";
            _pageparams.searchword = searchword;
            $("#searchinput").val(searchword);
        }

        _goodsListPage.loaddata(true);
    };
});
// 关闭搜索页
function showSearchPage() {
    $("#searchiframe").show();
    searchiframe.window.show($("#searchinput").val());
    searchiframe.window.loadSearchHistory();
}
// 关闭搜索页
function closeSearchPage() {
    $("#searchiframe").hide();
}

// 重写搜索页
function search(searchword) {};